import time
import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from protocol.decorators import edp_service, instant
from protocol.prelude import not_implemented
import cv2, json
import numpy as np
DBG = True

@edp_service
class CalibService:
    name = "py_calib"
    desc = "标定服务，Python版"
    category = "calibration"
    tasks = [
        "oc2p: Str->Json",
        "les7p: Str->Json",
        "fisheye: (FilePath,(Int,Int))->Json"
    ]
    def oc2p(self, inputs):
        not_implemented("请用builtin.calib")
    def les7p(self, inputs):
        not_implemented("请用builtin.calib")
    def fisheye(self, inputs):
        filepath = inputs[0]
        checkerboard = inputs[1]
        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
        objp = np.zeros((1, checkerboard[0] * checkerboard[1], 3), np.float32)
        objp[0,:,:2] = np.mgrid[0:checkerboard[0], 0:checkerboard[1]].T.reshape(-1, 2)
        import glob
        images = glob.glob(filepath)
        objpoints = []
        imgpoints = []
        for each in images:
            img = cv2.imread(each)
            gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
            ret, corners = cv2.findChessboardCorners(gray, checkerboard, cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.CALIB_CB_NORMALIZE_IMAGE)
            if ret == True:
                objpoints.append(objp)
                corners2 = cv2.cornerSubPix(gray, corners, (11,11),(-1,-1), criteria)
                imgpoints.append(corners2)
        ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
        res = {
            "mtx": mtx.tolist(),
            "dist": dist.tolist(),
            "rvecs": rvecs.tolist(),
            "tvecs": tvecs.tolist()
        }
        json.dump(res, "fisheye.json")
        return res

if __name__ == "__main__":
    # CalibService().fisheye(("", ()))
    CalibService.app.run(port=8100)
